<!-- 角色详情弹窗 -->
<script lang="ts" setup>
import { ref, computed } from 'vue'
import DuiForm from '@/common-ui/dui-form/index.vue'
import type { IDbFormItem } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import * as authApi from '@/api/auth'
import * as roleApi from '@/api/role'
import type { ElTreeSelect as MyTreeSelect } from 'element-plus'
import { ROLE_STATUS_LIST } from '../config'

const emits = defineEmits(['refresh'])

defineProps({
  // 标题
  title: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})

const treeRef = ref<InstanceType<typeof MyTreeSelect>>()
// 详情id
const infoId = ref('')
// 菜单树数据
const menuTreeData = ref<any[]>([])
// 弹窗表单数据
const ruleFormRef = ref<InstanceType<typeof DuiForm>>()
// 表单配置
const formConfig = computed<IDbFormItem[]>(() => {
  return [
    { label: '角色名称', prop: 'roleName', type: 'input', required: true, span: 12 },
    { label: '权限字符', prop: 'roleKey', type: 'input', required: true, span: 12 },
    { label: '角色顺序', prop: 'roleSort', type: 'number', required: true, span: 12 },
    { label: '状态', prop: 'status', type: 'radio', list: ROLE_STATUS_LIST, required: true, span: 12 },
    { label: '菜单权限', prop: 'resourceIds', type: 'slot', span: 24 },
    { label: '备注', prop: 'remark', type: 'textarea', span: 24 }
  ]
})
// 表单默认数据
const defaultData = {
  roleName: '',
  roleKey: '',
  roleSort: 10,
  status: '1',
  resourceIds: [],
  remark: ''
}
// 表单数据
const formData = ref(JSON.parse(JSON.stringify(defaultData)))
// 是否显示弹窗
const showDialog = ref(false)

initData()

/**
 * 打开弹窗并初始化数据
 */
function init(id?: string) {
  // 详情-编辑
  infoId.value = id ?? ''
  if (id) {
    roleApi.queryRole(id).then((resRole) => {
      if (resRole.success) {
        formData.value.roleName = resRole.data.data.roleName
        formData.value.roleKey = resRole.data.data.roleKey
        formData.value.roleSort = resRole.data.data.roleSort
        formData.value.status = resRole.data.data.status
        formData.value.remark = resRole.data.data.remark
      }
    })
    authApi.queryAuthByRoleId(id).then((resAuth) => {
      if (resAuth.success) {
        formData.value.resourceIds = resAuth.data?.data?.checkedKeys || []
      }
    })
  }
  // 添加
  else {
    formData.value = JSON.parse(JSON.stringify(defaultData))
  }
  showDialog.value = true
}

/**
 * 点击提交
 */
function submitClick() {
  formData.value.resourceIds = (treeRef.value?.getCheckedNodes(false, true) || []).map((item: any) => item.id)
  ruleFormRef.value
    ?.validate()
    .then(() => {
      // 添加
      let reqFunc = roleApi.addRole
      let params = formData.value
      // 修改
      if (infoId.value) {
        reqFunc = roleApi.editRole
        params = { ...formData.value, roleId: infoId.value }
      }
      reqFunc(params).then((res) => {
        if (res.success) {
          useNotic().success('提交成功！')
          showDialog.value = false
          emits('refresh')
        }
      })
    })
    .catch(() => {})
}

/**
 * 获取初始所需数据
 */
function initData() {
  authApi.getAuthList().then((res) => {
    if (res.success) {
      const menuList = res.data.data || []
      menuTreeData.value = handleNodeList(menuList)
    }
  })
}

/**
 * 处理树数据
 */
function handleNodeList(menuList: any[]) {
  const treeList: any[] = []
  const filterList = menuList
  filterList.forEach((item: any) => {
    item.label = item.title
    item.value = item.id
    if (item.pid == 0) {
      treeList.push(item)
    } else {
      for (let pItem of filterList) {
        if (item.pid == pItem.id) {
          if (!pItem.children) {
            pItem.children = []
          }
          pItem.children.push(item)
          break
        }
      }
    }
  })
  return treeList
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-form ref="ruleFormRef" :form-config="formConfig" :form-data="formData" :disabled="disabled">
      <template #resourceIdsSlot>
        <el-tree-select
          ref="treeRef"
          style="width: 100%"
          :data="menuTreeData"
          v-model="formData.resourceIds"
          :check-strictly="true"
          collapse-tags
          multiple
          show-checkbox
        />
      </template>
    </dui-form>
    <template #footer>
      <el-button @click="showDialog = false">关闭</el-button>
      <el-button type="primary" @click="submitClick" v-if="!disabled"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
